package com.ctgu.elasticsearch.config.rabbitMQ;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import com.ctgu.elasticsearch.entity.UserEntity;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @ ClassName UserQueueConsumer
 * @ Author Alex2
 * @ Date 2025/8/24 17:52
 **/
@Log4j2
@Component
public class UserQueueConsumer {

    private static final String TAG = "Alex";
    private final ElasticsearchClient elasticsearchClient;

    public UserQueueConsumer(ElasticsearchClient elasticsearchClient) {
        this.elasticsearchClient = elasticsearchClient;
    }

    // ================= 插入消费者 =================
    @RabbitListener(queues = UserQueueConfig.INSERT_USER_QUEUE)
    public void insertUser(UserEntity userEntity) throws IOException {
        elasticsearchClient.index(i -> i
                .index("user")
                .id(String.valueOf(userEntity.getId()))
                .document(userEntity)
        );
        log.info("{} ES 写入成功: {}", TAG, userEntity.getId());
    }

    // ================= 更新消费者 =================
    @RabbitListener(queues = UserQueueConfig.UPDATE_USER_QUEUE)
    public void updateUser(UserEntity userEntity) throws IOException {
        boolean exists = elasticsearchClient.exists(e -> e
                .index("user")
                .id(String.valueOf(userEntity.getId()))
        ).value();

        if (exists) {
            elasticsearchClient.update(u -> u
                            .index("user")
                            .id(String.valueOf(userEntity.getId()))
                            .doc(userEntity),
                    UserEntity.class
            );
            log.info("{} ES 更新成功: {}", TAG, userEntity.getId());
        } else {
            elasticsearchClient.index(i -> i
                    .index("user")
                    .id(String.valueOf(userEntity.getId()))
                    .document(userEntity)
            );
            log.info("{} ES 插入成功: {}", TAG, userEntity.getId());
        }
    }

    // ================= 删除消费者 =================
    @RabbitListener(queues = UserQueueConfig.DELETE_USER_QUEUE)
    public void deleteUser(Integer id) throws IOException {
        elasticsearchClient.delete(d -> d
                .index("user")
                .id(id.toString())
        );
        log.info("{} ES 删除成功: {}", TAG, id);
    }
}
